package com.cskaoyan.user.service.impl;

import com.alibaba.fastjson.JSON;

import com.cskaoyan.mall.commons.exception.ValidateException;
import com.cskaoyan.user.constants.UserRetCode;
import com.cskaoyan.user.dal.entitys.Member;
import com.cskaoyan.user.dal.entitys.UserVerify;
import com.cskaoyan.user.dal.persistence.MemberMapper;
import com.cskaoyan.user.dal.persistence.UserVerifyMapper;
import com.cskaoyan.user.dto.UserRegisterRequest;
import com.cskaoyan.user.dto.UserRegisterResponse;
import com.cskaoyan.user.service.IUserRegister;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;

import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.UUID;

@Slf4j
@Service
public class UserRegisterImpl implements IUserRegister {
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private UserVerifyMapper userVerifyMapper;
    @Value("${spring.mail.username}")
    String emileAddress;
    @Autowired
    JavaMailSender mailSender;

    /**
     * 向用户表中注入一条数据
     * 向用户验证表中插入注册数据
     * 发送邮件
     * @param userRegisterRequest
     * @return
     */
    @Override
    @Transactional
    public UserRegisterResponse userRegister(UserRegisterRequest userRegisterRequest) {
//        向用户表中注入一条数据
        UserRegisterResponse userRegisterResponse = new UserRegisterResponse();
        //数据不能为空
        userRegisterRequest.requestCheck();
        //用户名验证是否重复
        Example example = new Example(Member.class);
        example.createCriteria().andEqualTo("username", userRegisterRequest.getUserName());
        List<Member> members = memberMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(members)) {
            userRegisterResponse.setCode( UserRetCode.USERNAME_ALREADY_EXISTS.getCode());
            userRegisterResponse.setMsg(UserRetCode.USERNAME_ALREADY_EXISTS.getMessage());
            return userRegisterResponse;
        }
        //
        Member member = new Member();
        member.setEmail(userRegisterRequest.getEmail());
        member.setUsername(userRegisterRequest.getUserName());
        //密码加密处理

        String passWordByMD5 = DigestUtils.md5DigestAsHex(userRegisterRequest.getUserPwd().getBytes());
        member.setPassword(passWordByMD5);
        member.setIsVerified("N");
        Date date = new Date();
        member.setCreated(date);
        member.setState(1);
        member.setUpdated(date);

        int insert = memberMapper.insert(member);
        if (insert != 1) {
            userRegisterResponse.setMsg(UserRetCode.USERNAME_ALREADY_EXISTS.getMessage());
            userRegisterResponse.setCode(UserRetCode.USERNAME_ALREADY_EXISTS.getCode());
            return userRegisterResponse;
        }
        UserVerify userVerify = new UserVerify();
        userVerify.setUsername(userRegisterRequest.getUserName());
        userVerify.setIsExpire("N");
        userVerify.setIsVerify("N");
        userVerify.setRegisterDate(date);
        //uuid
        String s = userRegisterRequest.getUserName() + userRegisterRequest.getUserPwd() + UUID.randomUUID().toString();
        String uuid = DigestUtils.md5DigestAsHex(s.getBytes());
        userVerify.setUuid(uuid);
        int insert1 = userVerifyMapper.insert(userVerify);
        if (insert1 != 1) {
            userRegisterResponse.setMsg(UserRetCode.USER_REGISTER_VERIFY_FAILED.getMessage());
            userRegisterResponse.setCode(UserRetCode.USER_REGISTER_VERIFY_FAILED.getCode());
            return userRegisterResponse;
        }
        //邮件发送
        //http://localhost:8080/user/verify?uid=xxx&username=xxx
        //http://localhost:9999/user/verify?uid=xxx&username=xxx
        new Thread(new Runnable() {
            @Override
            public void run() {
                log.info("开始发送邮件");
                System.out.println("开始发送邮件");
                SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
                simpleMailMessage.setSubject("用户激活");
                simpleMailMessage.setTo(userRegisterRequest.getEmail());
                log.info("目标邮箱"+userRegisterRequest.getEmail());
                simpleMailMessage.setFrom(emileAddress);
                log.info("发送邮箱"+emileAddress);
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.append("http://localhost:9999/user/verify?").append("uid=").append(userVerify.getUuid()).append("&username=").append(userVerify.getUsername());
                log.info("构造发送内容："+stringBuilder.toString());
                simpleMailMessage.setText(stringBuilder.toString());
                mailSender.send(simpleMailMessage);
                log.info("发送执行完毕");
            }
        }).start();
//        Thread threadEmail = new Thread(() -> {
//            SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
//            simpleMailMessage.setSubject("用户激活");
//            simpleMailMessage.setTo(userRegisterRequest.getEmail());
//            simpleMailMessage.setFrom(emileAddress);
//            StringBuilder stringBuilder = new StringBuilder();
//            stringBuilder.append("http://localhost:9999/user/verify?").append("uid=").append(userVerify.getUuid()).append("&username=").append(userVerify.getUsername());
//            simpleMailMessage.setText(stringBuilder.toString());
//            mailSender.send(simpleMailMessage);
//        });
//        threadEmail.start();


//
        log.info("用户注册成功，注册参数request:{},{}", JSON.toJSON(userRegisterRequest),uuid);
        userRegisterResponse.setCode(UserRetCode.SUCCESS.getCode());
        userRegisterResponse.setMsg(UserRetCode.SUCCESS.getMessage());

        return userRegisterResponse;
    }

//    private void checkReptUserName(UserRegisterRequest userRegisterRequest) {
//        Example example = new Example(Member.class);
//        example.createCriteria().andEqualTo("username", userRegisterRequest.getUserName());
//        List<Member> members = memberMapper.selectByExample(example);
//        if (!CollectionUtils.isEmpty(members)) {
//            throw new ValidateException(UserRetCode.USERNAME_ALREADY_EXISTS.getMessage(), UserRetCode.USERNAME_ALREADY_EXISTS.getCode());
//        }
//        return;
//    }
}
